<?php
/**
 * Created by PhpStorm.
 * User: Jesse
 * Date: 2018/3/1
 * Time: 18:33
 */
namespace App\Admin\Extensions\Tools;

use Encore\Admin\Admin;
use Encore\Admin\Grid\Tools\AbstractTool;

class AjaxQuery extends AbstractTool
{
    protected $url;
    protected $label;
    protected $method;
    protected $data;

    public function __construct($url, $label = '操作', $method = 'get', $data = [])
    {
        if ($method == 'post') {
            $data['_token'] = 'LA.token';
        }
        $this->url = $url;
        $this->label = $label;
        $this->method = $method;
        $this->data = json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    public function script()
    {
        return <<<EOT

$('.grid-ajax-button').on('click', function() {

    $.ajax({
        method: '{$this->method}',
        url: '{$this->url}',
        data: {$this->data},
        success: function (res) {
            $.pjax.reload('#pjax-container');
            if (res.code == 1) {
                toastr.success(res.msg);
            } else {
                toastr.error('操作失败');
            }
        }
    });
});

EOT;
    }

    public function render()
    {
        Admin::script($this->script());

        return <<<EOT
        
<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-twitter btn-sm grid-ajax-button">
        <input type="checkbox">{$this->label}
    </label>
</div>

EOT;
    }
}